<template>
    <a-modal v-model="visibleDeliver" :confirmLoading="submitLoading" :closable="false" width="800px">
        <a-alert 
        v-if="isBtnShow==1 || isBtnShow==3"
        show-icon
        closable 
        style="margin-bottom:10px" 
        type="info">
        <template #message>
            <p>支持扩展名 .doc、.docx、.xls、.xlsx、.pdf、.png、.jpg、.gif、.jpeg</p>
            <p>单个文件大小不大于10MB，每次上传限制100个文件</p>
            <p>文件命名规格：身份证号（500110xxxxx_1.png,500110xxxxx_2.png）。其它命名规则无效。上传的文件必须和列表中存在的人员身份证一致。</p>
        </template>
        </a-alert>

        <a-progress v-if="count>0" status="normal" :percent="count" :format="getProgressText"/>

        <a-tabs :default-active-key="activeKey">
            <a-tab-pane key="1">
                <label slot="tab">
                    <span style="cursor: pointer;">图片</span>
                    <a-badge v-if="imgList.length!==0" :count="imgList.length" style="position: absolute;top:0;left:0;"></a-badge>
                </label>
                <a-empty  v-if="imgList.length ===0" description="暂无数据"/>
                <div class="voucker-pvp" v-for="(item,index) in imgList" :key="index">
                    <img :src="item.url" style="width:108px;height:108px;margin-right:4px;" />
                    <label class="voucker-name">{{item.name}}</label>
                    <p class="voucker-pmp" style="bottom:20px;">
                        <a-icon type="download" style="flex: 1;text-align: left;" @click="fileDownload(item.url)"/>
                        <a-popconfirm title="确定删除？" cancelText="取消" okText="确定" @confirm="delImg('imgs',index)">
                            <a-icon slot="icon" type="question-circle-o" style="color: red" />
                            <a-icon type="delete" v-if="isBtnShow==1 || isBtnShow==3"/>
                        </a-popconfirm>
                    </p>
                </div>
            </a-tab-pane>
            <a-tab-pane key="2">
                <label slot="tab">
                    <span style="cursor: pointer;">docx文档</span>
                    <a-badge v-if="docList.length!==0" :count="docList.length" style="position: absolute;top:0;left:0;"></a-badge>
                </label>
                <a-empty  v-if="docList.length ===0" description="暂无数据"/>
                <div class="voucker-pvp" v-for="(item,index) in docList" :key="index">
                    <img src="~@/assets/file_doc.png" style="width:108px;height:128px;margin-right:4px;" />
                    <label class="voucker-name">{{item.name}}</label>
                    <p class="voucker-pmp">
                        <a-icon type="download" style="flex: 1;text-align: left;" @click="fileDownload(item.url)"/>
                        <a-popconfirm title="确定删除？" cancelText="取消" okText="确定" @confirm="delImg('doc',index)">
                            <a-icon slot="icon" type="question-circle-o" style="color: red" />
                            <a-icon type="delete" v-if="isBtnShow==1 || isBtnShow==3" />
                        </a-popconfirm>
                    </p>
                </div>
            </a-tab-pane>
            <a-tab-pane key="3">
                <label slot="tab">
                    <span style="cursor: pointer;">xlsx文档</span>
                    <a-badge v-if="xlsxList.length!==0" :count="xlsxList.length" style="position: absolute;top:0;left:0;"></a-badge>
                </label>
                <a-empty  v-if="xlsxList.length ===0" description="暂无数据"/>
                <div class="voucker-pvp" v-for="(item,index) in xlsxList" :key="index">
                    <img src="~@/assets/file_xlsx.png" style="width:108px;height:128px;margin-right:4px;" />
                    <label class="voucker-name">{{item.name}}</label>
                    <p class="voucker-pmp">
                        <a-icon type="download" style="flex: 1;text-align: left;" @click="fileDownload(item.url)"/>
                        <a-popconfirm title="确定删除？" cancelText="取消" okText="确定" @confirm="delImg('xlsx',index)">
                            <a-icon slot="icon" type="question-circle-o" style="color: red" />
                            <a-icon type="delete" v-if="isBtnShow==1 || isBtnShow==3" />
                        </a-popconfirm>
                    </p>
                </div>
            </a-tab-pane>
            <a-tab-pane key="4">
                <label slot="tab">
                    <span style="cursor: pointer;">pdf文档</span>
                    <a-badge v-if="pdfList.length!==0" :count="pdfList.length" style="position: absolute;top:0;left:0;"></a-badge>
                </label>
                <a-empty  v-if="pdfList.length ===0" description="暂无数据"/>
                <div class="voucker-pvp" v-for="(item,index) in pdfList" :key="index">
                    <img src="~@/assets/file_pdf.png" style="width:108px;height:128px;margin-right:4px;" />
                    <label class="voucker-name">{{item.name}}</label>
                    <p class="voucker-pmp">
                        <a-icon type="download" style="flex: 1;text-align: left;" @click="fileDownload(item.url)"/>
                        <a-popconfirm title="确定删除？" cancelText="取消" okText="确定" @confirm="delImg('pdf',index)">
                            <a-icon slot="icon" type="question-circle-o" style="color: red" />
                            <a-icon type="delete" v-if="isBtnShow==1 || isBtnShow==3" />
                        </a-popconfirm>
                    </p>
                </div>
            </a-tab-pane>
        </a-tabs>

        <template slot="footer">
            <input type="file" ref="fileType" @change="handleChange" style="display: none;" multiple="multiple" />
            <a-button v-if="isBtnShow==1 || isBtnShow==3" type="primary" style="float: left" @click="$refs.fileType.click()">批量上传文件</a-button>
            <a-button @click="visibleDeliver = false">取消</a-button>
            <a-button v-if="isBtnShow==1 || isBtnShow==3" @click="handleOtehrFileOk" :disabled="btnState" type="primary">保存</a-button>
        </template>

    </a-modal>
</template>
<script>
import { 
    sysBaseUpload
} from '@/api/manage/base'
import { 
    previewFile
} from '@/utils/util'
import { allSettleUploadDelivery,allGetTaskDeliverables,allImportSttleDelivery } from '@/api/manage/sttle'
    export default {
        name: 'settleDeliver',
        data(){
            return {
                visibleDeliver:false,
                activeKey:"1",
                imgList:[],
                docList:[],
                xlsxList:[],
                pdfList:[],
                count:0,
                flag:false,
                isBtnShow:'',
                submitLoading:false
            }
        },
        computed: {
            btnState(){
                var flag = false;
                let newArray = [].concat(this.imgList,this.xlsxList,this.docList,this.pdfList);
                if(this.flag === true && this.count !== 100 || newArray.length === 0){
                    flag = true;
                }
                 if(newArray.length === 0){
                    this.count =0;
                }
                return flag;
            },
        },
        methods:{
            async add(row,types){
                const _this = this;
                this.flag = false;
                this.isBtnShow = types;
                this.activeKey = "1";
                this.count = 0;
                const imgType = ['png','jpg','jpeg','gif'];
                const xlsType = ['xls','xlsx'];
                const docType = ['docx','doc'];
                const pdfType = ['pdf'];
                this.imgList = [];
                this.xlsxList = [];
                this.docList = [];
                this.pdfList = [];
                if(row === true){
                    this.visibleDeliver = true;
                }else{
                    const {code,data} = await allGetTaskDeliverables(row.importId);
                    if(code === '1'){
                        data.forEach(item => {
                            let poIndex= item.content.lastIndexOf("/");
                            let idCardName = item.content.substr(poIndex+1);
                            let index= idCardName.lastIndexOf(".");
                            let fileName = idCardName.substring(0,index);

                            let fileIndex= item.content.lastIndexOf(".");
                            let _fileType = item.content.substr(fileIndex+1);

                            if(imgType.includes(_fileType)){
                                _this.imgList.push({url:item.content,name:fileName});
                            }else if(xlsType.includes(_fileType)){
                                _this.xlsxList.push({url:item.content,name:fileName})
                            }else if(docType.includes(_fileType)){
                                _this.docList.push({url:item.content,name:fileName})
                            }else if(pdfType.includes(_fileType)){
                                _this.pdfList.push({url:item.content,name:fileName})
                            }
                        })
                    }
                    this.visibleDeliver = true;
                }
            },
            delImg(type,index){
                if(type === 'imgs'){
                    this.imgList.splice(index,1);
                }else if(type === 'doc'){
                    this.docList.splice(index,1);
                }else if(type === 'xlsx'){
                    this.xlsxList.splice(index,1);
                }else if(type === 'pdf'){
                    this.pdfList.splice(index,1);
                }
            },
            fileDownload(_url){
                previewFile(_url);
            },
            getProgressText(percent){
                return`${percent}% `
            },
            async handleChange(e) {
                e.preventDefault();
                let _this = this;
                let fileList = e.target.files;
                if(fileList.length===0){
                    e.target.value= "";
                    return;
                }
                this.flag = true;
                this.count = 0;
                const fileType = ['pdf','doc','docx','xlsx','xls','png','jpg','gif','jpeg'];

                for (var i = 0;i < fileList.length;i++){
                    let isLt5M = fileList[i].size / 1024 / 1024 < 10
                    let fileIndex= fileList[i].name.lastIndexOf(".");
                    let idCardName = fileList[i].name.substring(0,fileIndex);
                    let _fileType = fileList[i].name.substr(fileIndex+1);
                    let formData = new FormData();
                    formData.append("file",fileList[i]);
                    sysBaseUpload(formData).then(response => {
                        const data = response.data;
                        if(!isLt5M){
                            this.count++;
                            this.$message.error('单个文件大小不能超过 10MB!');
                            return;
                        }
                        if (!fileType.includes(_fileType)) {
                            this.count++;
                            this.$message.error("文件格式错误");
                            e.target.value= "";
                            return;
                        }
                        this.count++;
                        const imgType = ['png','jpg','jpeg','gif'];
                        const xlsType = ['xls','xlsx'];
                        const docType = ['docx','doc'];
                        const pdfType = ['pdf'];
                        let _urlIndex= data.lastIndexOf(".");
                        let _urlName = data.substr(_urlIndex+1);
                        if(imgType.includes(_urlName)){
                            _this.imgList.push({url:data,name:idCardName});
                        }else if(xlsType.includes(_urlName)){
                            _this.xlsxList.push({url:data,name:idCardName})
                        }else if(docType.includes(_urlName)){
                            _this.docList.push({url:data,name:idCardName})
                        }else if(pdfType.includes(_urlName)){
                            _this.pdfList.push({url:data,name:idCardName})
                        }
                        if (this.count == fileList.length) {
                            this.count = 100;
                            this.flag = false;
                            e.target.value= "";
                            _this.$message.success("操作成功");
                        }
                    }).catch(error => {
                        _this.$message.error("网络不稳定，请重试或联系管理员");
                    })
                }
            },
            async handleOtehrFileOk(){
                let newArray = [];
                this.imgList.forEach(v=>{
                    let _params = {idCard:v.name,ossUrl:v.url}
                    newArray.push(_params);
                })
                this.xlsxList.forEach(v=>{
                    let _params = {idCard:v.name,ossUrl:v.url}
                    newArray.push(_params);
                })
                this.docList.forEach(v=>{
                    let _params = {idCard:v.name,ossUrl:v.url}
                    newArray.push(_params);
                })
                this.pdfList.forEach(v=>{
                    let _params = {idCard:v.name,ossUrl:v.url}
                    newArray.push(_params);
                })
                if(newArray.length === 0){
                    this.$message.error('最少上传一个文件！');
                    return;
                }
                let params = {};
                if(this.isBtnShow === 1){
                    params.taskId = this.$route.query.taskId;
                }else if(this.isBtnShow === 3){
                     params.settleBatchCode = this.$route.query.settleBatchCode;
                }
                params.files = newArray;
                this.submitLoading = true;
                const {code} = this.isBtnShow === 1? await allSettleUploadDelivery(params) : await allImportSttleDelivery(params);
                this.submitLoading = false;
                if(code === '1'){
                    this.$message.success('操作成功！');
                    this.visibleDeliver = false;
                    this.$emit("on-ok");
                }
            },
        }
    }
</script>